﻿using BCCommon;
using BCCommon.Enums;
using BCDto.Sim.Admin.Admin;
using BCDto.Sim.Admin.StaffOrganizationMappingRecord;
using BCService.Sim.Admin.Admin;
using BCService.Sim.Admin.AdminPermissionMappingPage;
using BCService.Sim.Admin.StaffOrganizationMappingRecord;
using BCService.Sim.Admin.TreePermission;
using BCService.Sim.Company.Company;
using BCService.Sim.Company.Department;
using BCService.Sim.Company.Position;
using BCService.TMS.Agent.AgentRecord;
using BCTMSRESTful.Configs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;

namespace BCTMSRESTful.Controllers.Management
{
    [RequireAuthorize(RoleType.Admin)]
#if DEBUG
    [SwaggerResponse(401, Description = "请求需要认证或者认证信息已过期。")]
    [SwaggerResponse(403, Description = "无权访问指定的功能。")]
#endif
    public class ManagementBaseController : BCTMSRESTfulAPIController
    {
        private IRedisService redisService;
        private IAdminService adminService;
        private ICompanyService companyService;
        private IDepartmentService departmentService;
        private IPositionService positionService;
        //private ISOBSettingService sobSettingService;
        private IAdminPermissionMappingPageService adminPermissionMappingPageService;
        private IStaffOrganizationMappingRecordService staffOrganizationMappingRecordService;
        private ITreePermissionRecordService treePermissionRecordService;
        private IAgentRecordService agentRecordService;
        /// <summary>
        /// 员工模型
        /// </summary>
        public AdminDto Admin { get; private set; }
        /// <summary>
        /// 员工角色记录
        /// </summary>
        public IEnumerable<StaffViewDto> StaffRoleRecord { get; set; }
        ///// <summary>
        ///// 账套设置
        ///// </summary>
        //public SOBSettingDto SobSetting { get; private set; }

        /// <summary>
        /// 重写OnActionExecuting方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            HttpContext httpContext = context.HttpContext;

            if (httpContext.User.Identity.IsAuthenticated && httpContext.User.Identity.Name.StartsWith("Admin:"))
            {
                if (long.TryParse(httpContext.User.Identity.Name.Substring(6), out long adminId))
                {
                    #region 初始化服务
                    redisService = httpContext.RequestServices.GetService<IRedisService>();
                    //sobSettingService = httpContext.RequestServices.GetService<ISOBSettingService>();
                    adminService = httpContext.RequestServices.GetService<IAdminService>();
                    companyService = httpContext.RequestServices.GetService<ICompanyService>();
                    departmentService = httpContext.RequestServices.GetService<IDepartmentService>();
                    positionService = httpContext.RequestServices.GetService<IPositionService>();
                    adminPermissionMappingPageService = httpContext.RequestServices.GetService<IAdminPermissionMappingPageService>();
                    staffOrganizationMappingRecordService = httpContext.RequestServices.GetService<IStaffOrganizationMappingRecordService>();
                    treePermissionRecordService = httpContext.RequestServices.GetService<ITreePermissionRecordService>();
                    agentRecordService = httpContext.RequestServices.GetService<IAgentRecordService>();
                    #endregion

                    this.Admin = adminService.GetAdminInfoByAdminId(adminId);

                    if (this.Admin != null)
                    {
                        this.Admin.Password = "";
                        this.GetStaffRoleRecord();
                        if (!this.Admin.IsSystemAccount)
                        {
                            if (this.Admin.AccountStatus == AccountStatus.Stop)
                            {
                                this.Admin.IsError = true;
                                this.Admin.ErrorMessage = "此账号已被关闭";
                            }
                            else if (this.Admin.AccountStatus == AccountStatus.Deleted)
                            {
                                this.Admin.IsError = true;
                                this.Admin.ErrorMessage = "此账号已被删除";
                            }

                            //var permissions = permissionService.GetByAdminId(this.Admin.AdminId);
                            //if (permissions.Any())
                            //{
                            //    this.Admin.AdminPermissions = permissions.ToArray();
                            //}

                            //var extensionPermissions = adminSpecificPermissionRecordService.Query(this.Admin.AdminId);
                            //if (extensionPermissions.Any())
                            //{
                            //    this.Admin.SpecificPermissions = extensionPermissions;
                            //}
                            //var belongareasTask = adminBelongAreaService.Query(this.Admin.AdminId);
                            //var belongareas = belongareasTask.GetAwaiter().GetResult();
                            //if (belongareas.Any())
                            //{
                            //    this.Admin.AdminBelongAreas = belongareas;
                            //}
                        }

                    }

                    //if (this.SobSetting == null)
                    //{
                    //    if (this.Admin.Department != null)
                    //    {
                    //        this.Admin.DepartmentId = this.Admin.Department.DepartmentId;
                    //        if (this.Admin.Department.DepartmentFunction.In("DepartmentFunction_SalesFinance", "DepartmentFunction_Finance", "DepartmentFunction_Insurance") || this.Admin.IsMain)
                    //        {
                    //            this.SobSetting = sobSettingService.GetEntity(this.Admin.CompanyId);

                    //            if (this.Admin.IsSystemAccount)
                    //            {
                    //                var redisDto = redisService.Get<SOBSettingDto>("SOBSetting_IsSystemAccount");
                    //                if (redisDto != null)
                    //                {
                    //                    this.SobSetting = redisDto;
                    //                }
                    //                if (this.SobSetting == null)
                    //                {
                    //                    this.Admin.IsError = true;
                    //                    this.Admin.ErrorMessage = "未设置企业账套信息，请先设置企业账套信息";
                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                }
                if (this.Admin == null)
                {
                    context.Result = this.Forbid();
                }
                if (this.Admin.IsError)
                {
                    throw new ArgumentException(this.Admin.ErrorMessage);
                }
            }

            base.OnActionExecuting(context);
        }

        #region 获取公司信息
        /// <summary>
        /// 获取公司信息
        /// </summary>
        private void GetCompany()
        {
            this.Admin.Company = companyService.Get(this.Admin.CompanyId);
            if (this.Admin.Company != null)
            {
                this.Admin.BusinessType = this.Admin.Company.BusinessType;
                this.Admin.BusinessTypeName = this.Admin.Company.BusinessTypeName;
            }
        }
        #endregion

        #region 获取部门信息
        /// <summary>
        /// 获取部门信息
        /// </summary>
        private void GetDepartment()
        {
            if (this.Admin.DepartmentId.HasValue)
            {
                this.Admin.Department = departmentService.Get(this.Admin.DepartmentId.Value);
            }
        }
        #endregion

        #region 获取岗位信息
        /// <summary>
        /// 获取岗位信息
        /// </summary>
        private void GetPosition()
        {
            var positionDto = this.positionService.Get(this.Admin.CompanyId,this.Admin.DepartmentId.Value,this.Admin.JobDutyKey);
            if (positionDto != null)
            {
                this.Admin.PositionId = positionDto.PositionId;
            }
        }
        #endregion

        #region 权限获取（仅控制页面与默认增删改查--已废弃）
        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="staffOrganizationMappingRecordId">员工组织映射记录Id</param>
        /// <returns></returns>
        private void GetPermission(long staffOrganizationMappingRecordId)
        {
            var result = adminPermissionMappingPageService.GetAdminPagePermissions(this.Admin.IsSystemAccount ? new Nullable<long>() : this.Admin.AdminId, staffOrganizationMappingRecordId);
            if (result.Item1.Any())
            {
                this.Admin.AdminPagePermissions = result.Item1;
            }
            if (result.Item2.Any())
            {
                this.Admin.PageMenus = result.Item2;
            }
        }
        #endregion

        #region 获取员工角色记录
        private void GetStaffRoleRecord()
        {
            var result = staffOrganizationMappingRecordService.GetList(this.Admin.AdminId);
            this.StaffRoleRecord = result;
            if (result.Any(p => p.IsActive))
            {
                var staff = result.Single(p => p.IsActive);
                this.SetStaffInfo(staff);
            }
        }
        #endregion

        #region 设置员工角色登录信息
        protected void SetRoleActive(long staffOrganizationMappingRecordId)
        {
            if (!this.StaffRoleRecord.Any(p => p.StaffOrganizationMappingRecordId == staffOrganizationMappingRecordId))
            {
                throw new ArgumentException("您无此角色，无法进入系统");
            }
            var staff = this.StaffRoleRecord.Single(p => p.StaffOrganizationMappingRecordId == staffOrganizationMappingRecordId);
            this.SetStaffInfo(staff);
            this.staffOrganizationMappingRecordService.SetActiveRole(staff.StaffOrganizationMappingRecordId);
        }
        #endregion

        #region 设置员工综合信息
        private void SetStaffInfo(StaffViewDto staff)
        {
            //this.GetPermission(staff.StaffOrganizationMappingRecordId);
            this.GetTreePermission(staff);
            this.Admin.CompanyId = staff.CompanyId;
            this.GetCompany();
            this.Admin.DepartmentId = staff.DepartmentId;
            this.GetDepartment();
            this.Admin.JobDutyKey = staff.JobDutyKey;
            this.Admin.JobTitleKey = staff.JobTitleKey;
            this.Admin.JobDuty = staff.JobDuty;
            this.Admin.JobTitle = staff.JobTitle;
            this.GetPosition();
            this.GetAgentRecord();
        }

        private void GetTreePermission(StaffViewDto staff)
        {
            var result = treePermissionRecordService.GetTreePermissions(this.Admin.IsSystemAccount ? new Nullable<long>() : staff.StaffOrganizationMappingRecordId);
            if (result.Item1.Any())
            {
                this.Admin.TreePermissions = result.Item1;
            }
            if (result.Item2.Any())
            {
                this.Admin.PageMenus = result.Item2;
            }
        }

        #endregion

        #region 设置代理商信息
        protected void GetAgentRecord()
        {
            if (this.Admin.CompanyId!=1)
            {
                this.Admin.AgentRecord = agentRecordService.Get(this.Admin);
            }
        }
        #endregion

        //#region 设置账套信息
        //protected void SettingSOB(SOBSettingDto sobSettingDto)
        //{
        //    if (this.Admin.IsSystemAccount)
        //    {
        //        this.SobSetting = sobSettingDto;
        //    }
        //}
        //#endregion

        //#region 特殊权限检查
        ///// <summary>
        ///// 特殊权限检查
        ///// </summary>
        ///// <param name="adminSpecificPermissionEnum">特殊权限枚举</param>
        ///// <returns></returns>
        //protected bool CheckSpecificPermissionExists(AdminSpecificPermissionEnum adminSpecificPermissionEnum)
        //{
        //    var list = this.Admin.SpecificPermissions;
        //    if (list != null && list.Any())
        //    {
        //        return list.Any(p => p.SpecificPermissionKey == adminSpecificPermissionEnum.ToString());
        //    }
        //    return false;
        //}
        //#endregion
    }
}
